package td3.model;

import java.awt.datatransfer.Transferable;

import javax.swing.JComponent;
import javax.swing.JTree;
import javax.swing.TransferHandler;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;

import td3.view.SuppView;

public class ContactNodeJPanelTransferHandler extends TransferHandler {

	private static final long serialVersionUID = 8807026538766261644L;
	private SuppView suppView;

	@Override
	public boolean importData(TransferSupport support) {
		if (canImport(support)) {
			try {
				try {
					Transferable t = support.getTransferable();
					DefaultMutableTreeNode dmt = (DefaultMutableTreeNode) t
							.getTransferData(ContactNodeTransferable.nodeFlavor);

					if (dmt.getUserObject() != null
							&& dmt.getUserObject() instanceof Contact) {
						Contact contact = (Contact) dmt.getUserObject();
						suppView.setContact(contact);
						return true;
					} else {
						return false;
					}
				} catch (Exception ex) {
					ex.printStackTrace();
				}
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
		return false;
	}

	public ContactNodeJPanelTransferHandler(SuppView suppView) {
		super();
		this.suppView = suppView;
	}

	@Override
	public int getSourceActions(JComponent component) {
		return TransferHandler.MOVE;// COPY MOVE LINK

	}

	@Override
	public ContactNodeTransferable createTransferable(JComponent c) {
		DefaultMutableTreeNode node = null;
		if (c instanceof JTree) {
			try {
				TreePath path = ((JTree) c).getSelectionPath();
				node = (DefaultMutableTreeNode) path.getLastPathComponent();
			} catch (Exception e) {
				System.err
						.println("ContactTransferHanlder.createTransferable(JComponent) FAILED");
				e.printStackTrace();
			}
			return new ContactNodeTransferable(node);
		}
		return null;
	}

	@Override
	public boolean canImport(TransferHandler.TransferSupport support) {
		return support.isDrop()
				&& support.getTransferable().isDataFlavorSupported(
						ContactNodeTransferable.nodeFlavor);
	}

}
